const express = require('express');
const router = express.Router();
const { pool } = require('../database');

// 获取预约号池列表
router.get('/', async (req, res) => {
  try {
    const { hospital_id, doctor_id, appointment_date, time_slot_type, is_available } = req.query;
    
    let sql = `
      SELECT ap.id, ap.hospital_id, ap.doctor_id, ap.appointment_date, ap.time_slot_type,
             ap.total_quota, ap.used_quota, ap.available_quota, ap.is_available,
             ap.created_at, ap.updated_at,
             h.name as hospital_name, d.name as doctor_name, dep.name as department_name
      FROM appointment_pools ap
      LEFT JOIN hospitals h ON ap.hospital_id = h.id
      LEFT JOIN doctors d ON ap.doctor_id = d.id
      LEFT JOIN departments dep ON d.department_id = dep.id
      WHERE 1=1
    `;
    
    const params = [];
    
    if (hospital_id) {
      sql += ' AND ap.hospital_id = ?';
      params.push(hospital_id);
    }
    
    if (doctor_id) {
      sql += ' AND ap.doctor_id = ?';
      params.push(doctor_id);
    }
    
    if (appointment_date) {
      sql += ' AND ap.appointment_date = ?';
      params.push(appointment_date);
    }
    
    if (time_slot_type) {
      sql += ' AND ap.time_slot_type = ?';
      params.push(time_slot_type);
    }
    
    if (is_available !== undefined) {
      sql += ' AND ap.is_available = ?';
      params.push(is_available === 'true');
    }
    
    sql += ' ORDER BY ap.appointment_date DESC, ap.time_slot_type ASC';
    
    const [rows] = await pool.execute(sql, params);
    
    res.json({
      success: true,
      data: rows,
      message: '获取预约号池列表成功'
    });
  } catch (error) {
    console.error('获取预约号池列表失败:', error);
    res.status(500).json({
      success: false,
      message: '获取预约号池列表失败',
      error: error.message
    });
  }
});

// 根据ID获取预约号池详情
router.get('/:id', async (req, res) => {
  try {
    const { id } = req.params;
    const [rows] = await pool.execute(`
      SELECT ap.id, ap.hospital_id, ap.doctor_id, ap.appointment_date, ap.time_slot_type,
             ap.total_quota, ap.used_quota, ap.available_quota, ap.is_available,
             ap.created_at, ap.updated_at,
             h.name as hospital_name, d.name as doctor_name, dep.name as department_name
      FROM appointment_pools ap
      LEFT JOIN hospitals h ON ap.hospital_id = h.id
      LEFT JOIN doctors d ON ap.doctor_id = d.id
      LEFT JOIN departments dep ON d.department_id = dep.id
      WHERE ap.id = ?
    `, [id]);
    
    if (rows.length === 0) {
      return res.status(404).json({
        success: false,
        message: '预约号池不存在'
      });
    }
    
    res.json({
      success: true,
      data: rows[0],
      message: '获取预约号池详情成功'
    });
  } catch (error) {
    console.error('获取预约号池详情失败:', error);
    res.status(500).json({
      success: false,
      message: '获取预约号池详情失败',
      error: error.message
    });
  }
});

// 创建预约号池
router.post('/', async (req, res) => {
  try {
    const {
      hospital_id, doctor_id, appointment_date, time_slot_type,
      total_quota, is_available
    } = req.body;
    
    // 验证必填字段
    if (!hospital_id || !doctor_id || !appointment_date || !time_slot_type) {
      return res.status(400).json({
        success: false,
        message: '医院ID、医生ID、预约日期和时段类型为必填项'
      });
    }
    
    // 验证医院是否存在
    const [hospital] = await pool.execute('SELECT id FROM hospitals WHERE id = ?', [hospital_id]);
    if (hospital.length === 0) {
      return res.status(400).json({
        success: false,
        message: '指定的医院不存在'
      });
    }
    
    // 验证医生是否存在
    const [doctor] = await pool.execute('SELECT id FROM doctors WHERE id = ?', [doctor_id]);
    if (doctor.length === 0) {
      return res.status(400).json({
        success: false,
        message: '指定的医生不存在'
      });
    }
    
    // 验证时段类型
    if (![1, 2].includes(time_slot_type)) {
      return res.status(400).json({
        success: false,
        message: '时段类型必须为1(上午)或2(下午)'
      });
    }
    
    // 检查是否已存在相同的号池
    const [existing] = await pool.execute(`
      SELECT id FROM appointment_pools 
      WHERE doctor_id = ? AND appointment_date = ? AND time_slot_type = ?
    `, [doctor_id, appointment_date, time_slot_type]);
    
    if (existing.length > 0) {
      return res.status(400).json({
        success: false,
        message: '该医生在指定日期和时段的号池已存在'
      });
    }
    
    const [result] = await pool.execute(`
      INSERT INTO appointment_pools (hospital_id, doctor_id, appointment_date, time_slot_type, total_quota, is_available)
      VALUES (?, ?, ?, ?, ?, ?)
    `, [
      hospital_id, doctor_id, appointment_date, time_slot_type,
      total_quota || 0, is_available !== false
    ]);
    
    res.status(201).json({
      success: true,
      data: { id: result.insertId },
      message: '创建预约号池成功'
    });
  } catch (error) {
    console.error('创建预约号池失败:', error);
    res.status(500).json({
      success: false,
      message: '创建预约号池失败',
      error: error.message
    });
  }
});

// 更新预约号池
router.put('/:id', async (req, res) => {
  try {
    const { id } = req.params;
    const {
      hospital_id, doctor_id, appointment_date, time_slot_type,
      total_quota, is_available
    } = req.body;
    
    // 检查号池是否存在
    const [existing] = await pool.execute('SELECT id FROM appointment_pools WHERE id = ?', [id]);
    if (existing.length === 0) {
      return res.status(404).json({
        success: false,
        message: '预约号池不存在'
      });
    }
    
    // 如果更新了医院ID，验证新医院是否存在
    if (hospital_id) {
      const [hospital] = await pool.execute('SELECT id FROM hospitals WHERE id = ?', [hospital_id]);
      if (hospital.length === 0) {
        return res.status(400).json({
          success: false,
          message: '指定的医院不存在'
        });
      }
    }
    
    // 如果更新了医生ID，验证新医生是否存在
    if (doctor_id) {
      const [doctor] = await pool.execute('SELECT id FROM doctors WHERE id = ?', [doctor_id]);
      if (doctor.length === 0) {
        return res.status(400).json({
          success: false,
          message: '指定的医生不存在'
        });
      }
    }
    
    // 验证时段类型
    if (time_slot_type && ![1, 2].includes(time_slot_type)) {
      return res.status(400).json({
        success: false,
        message: '时段类型必须为1(上午)或2(下午)'
      });
    }
    
    await pool.execute(`
      UPDATE appointment_pools SET
        hospital_id = ?, doctor_id = ?, appointment_date = ?, time_slot_type = ?,
        total_quota = ?, is_available = ?, updated_at = CURRENT_TIMESTAMP
      WHERE id = ?
    `, [
      hospital_id, doctor_id, appointment_date, time_slot_type,
      total_quota, is_available, id
    ]);
    
    res.json({
      success: true,
      message: '更新预约号池成功'
    });
  } catch (error) {
    console.error('更新预约号池失败:', error);
    res.status(500).json({
      success: false,
      message: '更新预约号池失败',
      error: error.message
    });
  }
});

// 删除预约号池
router.delete('/:id', async (req, res) => {
  try {
    const { id } = req.params;
    
    // 检查号池是否存在
    const [existing] = await pool.execute('SELECT id FROM appointment_pools WHERE id = ?', [id]);
    if (existing.length === 0) {
      return res.status(404).json({
        success: false,
        message: '预约号池不存在'
      });
    }
    
    // 删除号池（会级联删除相关预约）
    await pool.execute('DELETE FROM appointment_pools WHERE id = ?', [id]);
    
    res.json({
      success: true,
      message: '删除预约号池成功'
    });
  } catch (error) {
    console.error('删除预约号池失败:', error);
    res.status(500).json({
      success: false,
      message: '删除预约号池失败',
      error: error.message
    });
  }
});

// 更新号池状态
router.patch('/:id/status', async (req, res) => {
  try {
    const { id } = req.params;
    const { is_available } = req.body;
    
    if (typeof is_available !== 'boolean') {
      return res.status(400).json({
        success: false,
        message: 'is_available 必须为布尔值'
      });
    }
    
    await pool.execute(
      'UPDATE appointment_pools SET is_available = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?',
      [is_available, id]
    );
    
    res.json({
      success: true,
      message: `号池已${is_available ? '启用' : '禁用'}`
    });
  } catch (error) {
    console.error('更新号池状态失败:', error);
    res.status(500).json({
      success: false,
      message: '更新号池状态失败',
      error: error.message
    });
  }
});

// 更新号池配额
router.patch('/:id/quota', async (req, res) => {
  try {
    const { id } = req.params;
    const { total_quota } = req.body;
    
    if (typeof total_quota !== 'number' || total_quota < 0) {
      return res.status(400).json({
        success: false,
        message: 'total_quota 必须为非负数字'
      });
    }
    
    // 检查配额是否足够
    const [pool] = await pool.execute('SELECT used_quota FROM appointment_pools WHERE id = ?', [id]);
    if (pool.length === 0) {
      return res.status(404).json({
        success: false,
        message: '预约号池不存在'
      });
    }
    
    if (total_quota < pool[0].used_quota) {
      return res.status(400).json({
        success: false,
        message: '总配额不能小于已使用配额'
      });
    }
    
    await pool.execute(
      'UPDATE appointment_pools SET total_quota = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?',
      [total_quota, id]
    );
    
    res.json({
      success: true,
      message: '更新号池配额成功'
    });
  } catch (error) {
    console.error('更新号池配额失败:', error);
    res.status(500).json({
      success: false,
      message: '更新号池配额失败',
      error: error.message
    });
  }
});

// 生成预约号池
router.post('/generate', async (req, res) => {
  try {
    const { hospital_id, doctor_id, start_date } = req.body;
    
    if (!hospital_id || !doctor_id || !start_date) {
      return res.status(400).json({
        success: false,
        message: '医院ID、医生ID和开始日期为必填项'
      });
    }
    
    // 调用存储过程生成号池
    const [result] = await pool.execute('CALL GenerateAppointmentPools(?, ?, ?)', [
      hospital_id, doctor_id, start_date
    ]);
    
    res.json({
      success: true,
      data: result[0],
      message: '生成预约号池成功'
    });
  } catch (error) {
    console.error('生成预约号池失败:', error);
    res.status(500).json({
      success: false,
      message: '生成预约号池失败',
      error: error.message
    });
  }
});

module.exports = router;
